<template>
  <div class="app-container market-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px" class="search-form">
      <el-form-item label="市场名称" prop="marketName">
        <el-input
          v-model="queryParams.marketName"
          placeholder="请输入市场名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在地区" prop="region">
        <el-cascader
          v-model="queryParams.region"
          :options="regionOptions"
          :show-all-levels="false"
          placeholder="请选择所在地区"
          clearable
          @change="handleRegionChange"
          style="width: 200px;"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['yjnb:market:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['yjnb:market:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['yjnb:market:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['yjnb:market:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="marketList" 
      @selection-change="handleSelectionChange"
      class="market-table"
      :header-cell-style="{background:'#f5f7fa',color:'#606266',fontWeight:'600'}"
      stripe
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="序号" align="center" width="70">
        <template slot-scope="scope">
          {{ (queryParams.page - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="市场编号" align="center" prop="marketId" min-width="100">
        <template slot-scope="scope">
          <el-tag size="small" effect="plain" type="info">
            <i class="el-icon-s-flag"></i> #{{ scope.row.marketId }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="市场名称" align="center" prop="marketName" min-width="180" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="market-name">
            <i class="el-icon-office-building"></i> {{ scope.row.marketName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="所在地区" align="center" prop="region" min-width="180" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span class="region-text">
            <i class="el-icon-location-outline"></i> {{ scope.row.region }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" min-width="160">
        <template slot-scope="scope">
          <div class="time-wrapper">
            <i class="el-icon-time"></i>
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="modifyTime" min-width="160">
        <template slot-scope="scope">
          <div class="time-wrapper">
            <i class="el-icon-edit-outline"></i>
            <span>{{ parseTime(scope.row.modifyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['yjnb:market:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['yjnb:market:remove']"
            style="color: #F56C6C;"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改农贸市场对话框 -->
    <el-dialog 
      :title="title" 
      :visible.sync="open" 
      width="500px" 
      append-to-body 
      @close="cancel"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="市场名称" prop="marketName">
          <el-input 
            v-model="form.marketName" 
            placeholder="请输入市场名称"
          />
        </el-form-item>
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="form.region"
            :options="regionOptions"
            :show-all-levels="false"
            placeholder="请选择所在地区"
            style="width: 100%;"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMarket, getMarket, delMarket, addMarket, updateMarket, exportMarket } from "@/api/yjnb/market";
import { getRegionCascader } from "@/api/yjnb/region";

export default {
  name: "Market",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 农贸市场表格数据
      marketList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 地区选项 - 三级级联格式（省-市-区），从后端动态加载
      regionOptions: [],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        marketName: null,
        region: null,
        beginTime: null,
        endTime: null
      },

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        marketName: [
          { required: true, message: "市场名称不能为空", trigger: "blur" },
          { min: 2, max: 100, message: '市场名称长度必须介于 2 和 100 之间', trigger: 'blur' }
        ],
        region: [
          { 
            required: true, 
            message: "所在地区不能为空", 
            trigger: "change",
            validator: (rule, value, callback) => {
              if (!value || value.length !== 3) {
                callback(new Error('请选择完整的省、市、区'));
              } else {
                callback();
              }
            }
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getRegionList();
  },
  computed: {
    
  },
  methods: {
    /** 获取级联选择器区域数据 */
    getRegionList() {
      getRegionCascader({ status: 1 }).then(response => {
        if (response.code === 200 && response.data) {
          // 后端已返回树形结构，直接使用
          this.regionOptions = response.data;
        }
      }).catch(error => {
        console.error('获取区域数据失败:', error);
        this.regionOptions = [];
      });
    },
    
    /** 查询农贸市场列表 */
    getList() {
      this.loading = true;
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.beginTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
      
      // 在发送请求前，将级联选择的数组转换为字符串（省-市-区格式）
      const params = {...this.queryParams};
      if (params.region && params.region.length === 3) {
        params.region = `${params.region[0]}-${params.region[1]}-${params.region[2]}`;
      } else {
        params.region = null;
      }
      
      listMarket(params).then(response => {
        this.marketList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        marketId: null,
        marketName: null,
        region: null
      };
      this.resetForm("form");
    },
    
    // 处理地区级联选择变化
    handleRegionChange() {
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.marketId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加农贸市场";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const marketId = row.marketId || this.ids[0];
      getMarket(marketId).then(response => {
        // 解析地区字符串为级联数组格式（省-市-区）
        const data = response.data;
        if (data.region && data.region.includes('-')) {
          // 将"省-市-区"格式的字符串拆分为数组
          data.region = data.region.split('-');
        }
        this.form = data;
        this.open = true;
        this.title = "修改农贸市场";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 创建提交数据，将级联数组转换为"省-市-区"格式字符串
          const submitData = {...this.form};
          if (submitData.region && submitData.region.length === 3) {
            submitData.region = `${submitData.region[0]}-${submitData.region[1]}-${submitData.region[2]}`;
          }
          
          if (submitData.marketId != null) {
            updateMarket(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMarket(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 统一处理为数组格式
      const marketIds = row && row.marketId ? [row.marketId] : this.ids;
      
      // 检查是否有选中的数据
      if (!marketIds || marketIds.length === 0) {
        this.$message.warning('请选择要删除的市场');
        return;
      }
      
      // 构建提示信息
      const marketNames = row && row.marketId 
        ? row.marketName 
        : this.marketList.filter(item => this.ids.includes(item.marketId)).map(item => item.marketName).join('、');
      
      // 确认删除
      this.$modal.confirm('是否确认删除市场"' + marketNames + '"？').then(() => {
        // 调用批量删除接口，传递 ID 数组
        return delMarket(marketIds);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      exportMarket().then(response => {
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement('a');
        link.href = url;
        link.download = `农贸市场_${new Date().getTime()}.xlsx`;
        link.click();
        window.URL.revokeObjectURL(url);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.market-container {
  /* 搜索表单样式 */
  .search-form {
    background: #fff;
    padding: 18px 16px 6px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    ::v-deep .el-form-item {
      margin-bottom: 12px;
    }
    
    ::v-deep .el-input__inner,
    ::v-deep .el-input__inner:focus {
      transition: all 0.3s ease;
    }
    
    ::v-deep .el-input__inner:hover {
      border-color: #c0c4cc;
    }
    
    ::v-deep .el-input__inner:focus {
      border-color: #409EFF;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }
  }

  /* 表格容器样式 */
  .market-table {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    overflow: hidden;

    /* 市场名称样式 */
    .market-name {
      color: #303133;
      font-weight: 600;
      font-size: 14px;
      cursor: pointer;
      transition: color 0.3s;

      i {
        color: #409EFF;
        margin-right: 6px;
        font-size: 16px;
      }

      &:hover {
        color: #409EFF;
      }
    }

    /* 地区样式 */
    .region-text {
      color: #606266;
      font-size: 13px;

      i {
        color: #67C23A;
        margin-right: 4px;
      }
    }

    /* 时间样式 */
    .time-wrapper {
      color: #909399;
      font-size: 13px;

      i {
        margin-right: 4px;
        color: #C0C4CC;
      }
    }

    /* 表格行悬停效果 */
    ::v-deep .el-table__row {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }
    }
  }

  /* 按钮行样式 */
  .mb8 {
    background: #fff;
    padding: 12px 16px;
    border-radius: 8px;
    margin-bottom: 16px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    ::v-deep .el-button {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
      }

      &:active {
        transform: translateY(0);
      }
    }
  }

  /* 分页样式 */
  ::v-deep .pagination-container {
    margin-top: 16px;
    background: #fff;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    
    /* 分页按钮动画 */
    .el-pager li {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
      }
      
      &.active {
        animation: pulse 0.5s ease;
      }
    }
    
    @keyframes pulse {
      0% {
        transform: scale(1);
      }
      50% {
        transform: scale(1.1);
      }
      100% {
        transform: scale(1);
      }
    }
    
    /* 上一页/下一页按钮动画 */
    .btn-prev, .btn-next {
      transition: all 0.3s ease;
      
      &:hover {
        transform: scale(1.1);
        color: #409EFF;
      }
    }
  }
}

</style>
